package model

type PostType struct {
	Ip     uint64 `gorm:"primary_key;auto_increment"`
	IpName string `gorm:"column:ipname;not null" json:"ipname" binding:"required" form:"ipname"`
	//关联字段
	Posts []Post `gorm:"many2many:post_type_maps" binding:"-"`
}

type PostTypeMap struct {
	Pid uint64 `gorm:"column:post_pid;primaryKey" json:"post_pid"`
	Ip  uint64 `gorm:"column:post_type_ip;primaryKey" json:"post_type_ip"`
}

type PostTypeRequest struct {
	IP []uint64 `json:"ip" binding:"required"` // 使用uint64类型接收
}

// 通过类型找post
func (a *PostType) GetPostByType() error {
	return DB.Self.Preload("Posts").First(&a).Error
}

// 新增post——type记录
func CreatePostType(pid uint64, ip uint64) error {
	var existing PostTypeMap
	DB.Self.Where("pid = ? AND ip = ?", pid, ip).First(&existing)
	if existing.Pid == 0 && existing.Ip == 0 {
		// 创建新关联
		pt := PostTypeMap{Pid: pid, Ip: ip}
		if err := DB.Self.Create(&pt).Error; err != nil {
			return nil
		}
	}
	return nil
}

// 新增post
func (ptm *PostTypeMap) Create() error {
	return DB.Self.Create(&ptm).Error
}
